package com.narunas.model.managers{
	
	
	//import com.rte.utils.*;
	
	import flash.events.IEventDispatcher;
	import flash.external.ExternalInterface;
	
	public class ServiceManager
	{
		// SINGLETON
		private static var _SF:ServiceManager;
		private var isEIAvailable:Boolean = false;
		
		// Asynchronous services availabe through JS methods
		private static const SERVICE:String = "Services.asynchExec";
		
		
		// CALLEE scope
		private var scope:Object;
		
		
		public function ServiceManager(target:IEventDispatcher=null)
		{
			super();
			if(_SF) return; _SF = this;
			
		}
		/**
		 * return - an instance of the ServiceManagerFlex
		 * */
		public static function getInstance():ServiceManagerFlex
		{
			return _SF;
			
		}
		
		// Asynchronous call - fire and forget
		public function asynchExec(o:Object):void
		{
			isEIAvailable = ExternalInterface.available;
			
			if(isEIAvailable)
			{
		
				ExternalInterface.call(SERVICE, o.call, ObjToXML.strToXMLString(o.params));
			}
			
		}
		
		
		// Syncronous REST call expecting an immediate response
		// this method is called from the BussinesLayerProxy
		
		public function syncExec(o:Object):AsyncToken
		{
			var hs:HTTPService = new HTTPService();
			hs.method = "POST";
			hs.resultFormat="xml";
			hs.contentType="application/xml";
			hs.request = ObjToXML.strToXML(o.params); // this is now converted to proper XML object to be sent
			//hs.url = scope.rootP+":"+scope.portP+"/bv/lws/syncExec?service=" + o.call;
			var tk:AsyncToken = hs.send();
			
			//collecting garbage 
			hs = null;
			
			// returning
			return tk;
			
		}
		
		/**
		 *  the bellow COULD be handled more elegantly - good enough for now
		 * 
		 * */
		public function receiveAsync(st:String, obj:Object):void
		{
			scope.receiveDWR(st, obj);
		}
		
		/**
		 *  sc - object this is the flex scope that will be listening for the async DWR call
		 *  Well - I am sure there is a better way.
		 * */
		public function setFlashScope(sc:Object):void
		{
			scope = sc;
			ExternalInterface.addCallback("receiveAsync",receiveAsync);
			
		}
	}
}